package com.huluspace.springtransactional.service;

import com.huluspace.springtransactional.model.Role;
import com.huluspace.springtransactional.model.User;
import com.huluspace.springtransactional.repository.UserRepository;
import com.huluspace.springtransactional.security.CustomUserDetails;
import com.huluspace.springtransactional.security.JwtUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class JwtAuthService {

  final private JwtUtil jwtUtil;
  final private UserRepository userRepository;
  public JwtAuthService(JwtUtil jwtUtil, UserRepository userRepository) {
    this.jwtUtil = jwtUtil;
    this.userRepository = userRepository;
  }

  // 基于JWT鉴权并封装用户详情
  public CustomUserDetails loadUserByToken(String token) {
    if (!jwtUtil.validateToken(token)) {
      throw new RuntimeException("Invalid token");
    }
    String username = jwtUtil.extractUserName(token);
    User user = userRepository.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found"));
    List<GrantedAuthority> authorities = getAuthoritiesByUserName(username);
    return new CustomUserDetails(user.getId(), user.getUsername(), "", authorities);
  }

  // 获取用户权限
  private List<GrantedAuthority> getAuthoritiesByUserName(String username) {
    return findRolesByUsername(username).stream()
        .map(role -> new SimpleGrantedAuthority(role.trim()))
        .collect(Collectors.toList());
  }

  // 事务内访问懒加载属性
  private List<String> findRolesByUsername(String username) {
    return userRepository.findByUsernameWithRoles(username)
        .map(user -> user.getRoles().stream()
            .map(Role::getName)
            .toList())
        .orElse(List.of());
  }
}
